package com.wj.springboot2demo.ws;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

@Component
@ServerEndpoint("/websocket/{imUserId}/{wsToken}")
public class WebSocketTest {

    private Session session;
    
    private static CopyOnWriteArraySet<WebSocketTest> sessions = new CopyOnWriteArraySet<>();
    
    @OnOpen
    public void onOpen(Session session, @PathParam("imUserId") String imUserId, @PathParam("wsToken") String wsToken) {
        
        if(imUserId.length() <= 4) {
            try {
                this.session.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ;
        }
        
        this.session = session;
        sessions.add(this);
        System.out.println("创建连接：" + session.getId() + ", user : " + imUserId + "/" + wsToken);
    }
    
    @OnClose
    public void onClose() {
        sessions.remove(this);
        System.out.println("创建连接：" + session.getId());
    }
    
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误：连接重置");
    }
    
    //给所有人发信息
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("广播消息：" + session.getId() + " : " + message);
        
        try {
            for(WebSocketTest t : sessions) {
                t.sendMessage(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
}
